﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq语句排序求和求平均数
{
    class Program
    {
        static void Main(string[] args)
        {
            //随机数存集合中
            int j = 0;
            List<int> list = new List<int>();
            Random random = new Random();
            for(int i = 0; i < 100; i++)
            {
                list.Add(random.Next(10000));
            }

            //对随机数排序
            Console.WriteLine();
            Console.WriteLine("对随机数排序：");
            var query = from x in list
                        orderby x
                        select x;
            list = query.ToList();
            foreach (int i in list)
            {
                Console.Write(i + "  ");

                if (j == 9)
                {
                    Console.WriteLine();
                    j = 0;
                }
                else
                {
                    j++;
                }
            }
            Console.WriteLine();

            //求和，求平均数
            var sumResult = from s in list
                            //根据整个list分组 将分组后的结果集存入p
                            group s by list into p
                            //此时结果集已经是p，所以要从p中取数据。
                            select new
                            {
                                sum = p.Sum(x => x),
                                average = p.Average(x => x),
                            };
            foreach (var item in sumResult)
            {
                Console.WriteLine("总和:" + item.sum);
                Console.WriteLine();
                Console.WriteLine("平均值：" + item.average);
            }
        }
    }
}
